package org.noka.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nokatag.password.AESPlus;
import org.nokatag.system.Concest;

/**
 * cookie操作类
 * @author rebin
 * @2015-11-12
 */
public class CookieUtil {
	/**
	 * 设置cookie
	 * @param key cookie的key
	 * @param value cookie的value
	 */
	public void setCookie(HttpServletResponse response,String key,String value){
		response.setHeader("P3P","CP=\"CURa ADMa DEVa PSAo PSDo OUR BUS UNI PUR INT DEM STA PRE COM NAV OTC NOI DSP COR\"");
		StringBuffer sb = new StringBuffer();
		String v2 = AESPlus.encrypt(value, Concest.SQLKEY);//加密
		sb.append(key+"="+v2);
		sb.append(";path=/");
		if(null!=Concest.COOKIE_DOMAIN)
			sb.append(";domain="+Concest.COOKIE_DOMAIN);
		sb.append(";HttpOnly");
		response.addHeader("Set-Cookie",sb.toString());
	}
	
	/**
	 * 对比key
	 * @param request
	 * @param value
	 * @return
	 */
	public boolean CookieImg(HttpServletRequest request,String key,String value){
		Cookie[] cks = request.getCookies();
		if(null==key)
			key = "noka_code";
		for(int i=0;i<cks.length;i++){
			if(key.equals(cks[i].getName())){
				String sk = AESPlus.decrypt(cks[i].getValue(), Concest.SQLKEY);//解密
				if(value.equals(sk))
					return true;
				break;
			}
		}
		return false;
	}
	/**
	 * 获取解密之后的cookies
	 * @param request
	 * @param key
	 * @return
	 */
	public String getCookieE(HttpServletRequest request,String key){
		Cookie[] cks = request.getCookies();
		if(null!=key){
			for(int i=0;i<cks.length;i++){
				if(key.equals(cks[i].getName())){
					String sk = AESPlus.decrypt(cks[i].getValue(), Concest.SQLKEY);//解密
					return sk;
				}
			}
		}
		return null;
	}
}
